<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class dao extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('make:dao')
            ->addArgument('name')
            ->setDescription('Create a new dao');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $name = trim($input->getArgument('name'));
        $msg = $this->create($name);
        $output->writeln($msg);
    }

    protected function create($name)
    {
        $arr = explode('/',$name);

        $name = array_pop($arr);
        if(!$name) return '名称不正确';

        $baseNamespace = "app\\common\\";
        $baseDir = app_path().'common';

        $DR = DIRECTORY_SEPARATOR;
        $BaseStubPath = __DIR__.$DR.'stubs'.$DR;


        $map = [
            ['type'=>'model','dir'=>'model','append'=>''],
            ['type'=>'dao','dir'=>'dao','append'=>'Dao'],
            ['type'=>'repository','dir'=>'repositories','append'=>'Repository'],
        ];

        foreach ($map as $item){
            //路径
            $path = $baseDir.$DR.$item['dir'].(count($arr) ? ($DR.join($DR,$arr)) : '');
            if(!is_dir($path)) mkdir($path,755,true);
            //命名空间
            $nameSpace = $baseNamespace.$item['dir'].(count($arr) ? ("\\".join("\\",$arr)) : '');
            //文件名  //类名
            $fileName = $name.$item['append'];
            $stubPath = $BaseStubPath.$item['type'].'.stub';

            $replaceData = [
                '{%classname%}'=>$fileName,
                '{%namespace%}'=>$nameSpace
            ];

            if($item['type'] == 'model'){
                $pk = Db::name(uncamelize($fileName))->getPk();
                $replaceData['{%pk%}'] = $pk;
                $replaceData['{%tableName%}'] = uncamelize($fileName);
            }

            if($item['type'] == 'dao'){
                $replaceData['{%use%}'] = $baseNamespace.'model'.(count($arr) ? ("\\".join("\\",$arr)) : '').("\\").$name;
            }

            if($item['type'] == 'repository'){
                $replaceData['{%use%}'] = $baseNamespace.'dao'.(count($arr) ? ("\\".join("\\",$arr)) : '').("\\").$name."Dao";
            }

            if(!is_file($path.$DR.$fileName.'.php')){
                $content = file_get_contents($stubPath);
                $fileContents = str_replace(
                   array_keys($replaceData),array_values($replaceData),$content);
                file_put_contents($path.$DR.$fileName.'.php',$fileContents);
            }

        }

        return 'make' . ':' . $name . '[dao,model,repository]successful!';

        $daoName = $name.'Dao';
        $daoPathname = $baseDir.DIRECTORY_SEPARATOR.'dao'.DIRECTORY_SEPARATOR.$daoName.'.php';
        $daoNamespace = $baseNamespace.'\\dao';

        $modelName = $name;
        $modelNamespace =  $baseNamespace.'\\model';
        $modelPathname =  $baseDir.DIRECTORY_SEPARATOR.'model'.DIRECTORY_SEPARATOR.$modelName.'.php';

        $repName = $name.'Repository';
        $repNamespace =  $baseNamespace.'\\repositories';
        $repPathname =  $baseDir.DIRECTORY_SEPARATOR.'repositories'.DIRECTORY_SEPARATOR.$repName.'.php';

        //生成dao
        if (!is_file($daoPathname)) {
            $content = file_get_contents($stubPath.'dao.stub');
            $fileContents = str_replace(
                ['{%classname%}','{%use%}','{%namespace%}','{%modelName%}'],[$daoName,$modelNamespace.'\\'.$modelName,$daoNamespace,$modelName],$content);
            file_put_contents($daoPathname,$fileContents);
        }

        //生成model
        if(!is_file($modelPathname)){
            $tableName = uncamelize($name);
            $pk = Db::name($tableName)->getPk();

            $mContent = file_get_contents($stubPath.'model.stub');
            $mFileContents = str_replace(
                ['{%classname%}','{%pk%}','{%namespace%}','{%tableName%}'],[$modelName,$pk,$modelNamespace,$tableName],$mContent);
            file_put_contents($modelPathname,$mFileContents);
        }

        //生成repository
        if(!is_file($repPathname)){
            $rContent = file_get_contents($stubPath.'repository.stub');
            $rFileContents = str_replace(
                ['{%classname%}','{%use%}','{%namespace%}','{%dao%}'],[$repName,$daoNamespace.'\\'.$daoName,$repNamespace,$daoName],$rContent);
            file_put_contents($repPathname,$rFileContents);
        }

       return 'make' . ':' . $name . '[dao,model,repository]successful!';
    }

}
